<template>
  <div class="prompt-manage-container">
    <div class="page-header">
      <h2 class="page-title">提示词管理</h2>
      <a-button type="primary" @click="showCreateModal">
        <plus-outlined /> 创建提示词
      </a-button>
    </div>

    <div class="prompt-list">
      <a-table
        :columns="columns"
        :data-source="promptList"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">{{ record.type }}</a-tag>
          </template>
          <template v-if="column.key === 'tags'">
            <a-space wrap>
              <a-tag v-for="tag in record.tags" :key="tag">{{ tag }}</a-tag>
            </a-space>
          </template>
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="editPrompt(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此提示词吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deletePrompt(record.id)"
              >
                <a class="delete-link">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 创建/编辑提示词对话框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑提示词' : '创建提示词'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="700px"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" layout="vertical">
        <a-form-item label="提示词名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入提示词名称" />
        </a-form-item>
        
        <a-form-item label="类型" name="type">
          <a-select v-model:value="formState.type">
            <a-select-option value="system">系统提示词</a-select-option>
            <a-select-option value="user">用户提示词</a-select-option>
            <a-select-option value="assistant">助手提示词</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="内容" name="content">
          <a-textarea v-model:value="formState.content" :rows="8" placeholder="请输入提示词内容" />
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formState.description" :rows="3" placeholder="请输入提示词描述" />
        </a-form-item>
        
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="formState.tags"
            mode="tags"
            style="width: 100%"
            placeholder="请输入标签"
          ></a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import type { PromptItem, PromptType } from '../types/prompt';

// 表格列定义
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '标签',
    key: 'tags'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
  {
    title: '操作',
    key: 'operation',
  },
];

// 提示词列表和加载状态
const promptList = ref<PromptItem[]>([]);
const loading = ref(false);

// 表单相关
const formRef = ref();
const modalVisible = ref(false);
const isEdit = ref(false);
const currentPrompt = ref<PromptItem | null>(null);

// 表单状态
const formState = reactive({
  name: '',
  type: 'system' as 'system' | 'user' | 'assistant',
  content: '',
  description: '',
  tags: [] as string[]
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入提示词名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择提示词类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入提示词内容', trigger: 'blur' }]
};

// 获取类型对应的颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    system: 'blue',
    user: 'green',
    assistant: 'purple'
  };
  return colorMap[type] || 'default';
};

// Mock数据生成
const generateMockPromptList = () => {
  return [
    {
      id: '1',
      name: '问题解答模板',
      type: 'system' as PromptType,
      content: '你是一个专业的解答助手，请根据用户的问题提供清晰、准确的答案。回答应该简洁明了，并尽可能提供具体的例子或参考资料。如果不确定，请表明这是基于现有知识的推测。',
      description: '用于问答场景的系统提示词，引导AI生成清晰的回答',
      tags: ['问答', '解释', '通用'],
      createdAt: '2023-10-01',
      updatedAt: '2023-10-01'
    },
    {
      id: '2',
      name: '创意写作助手',
      type: 'system' as PromptType,
      content: '你是一个创意写作助手，专长于生成有创意和富有想象力的内容。用户可能会要求你写故事、诗歌或其他创意文本。请确保你的回答有创意、原创，并符合用户的要求。',
      description: '用于创意写作的系统提示词，鼓励AI生成有创意的内容',
      tags: ['写作', '创意', '故事'],
      createdAt: '2023-10-02',
      updatedAt: '2023-10-02'
    },
    {
      id: '3',
      name: '代码审查专家',
      type: 'system' as PromptType,
      content: '你是一个专业的代码审查专家，擅长分析代码质量、性能和安全性。请对用户提供的代码进行详细分析，指出潜在问题，并提供改进建议。考虑代码可读性、性能优化、安全漏洞和最佳实践。',
      description: '用于代码审查的系统提示词，帮助识别代码问题并提供改进建议',
      tags: ['编程', '代码审查', '技术'],
      createdAt: '2023-10-03',
      updatedAt: '2023-10-03'
    },
    {
      id: '4',
      name: '用户问题模板',
      type: 'user' as PromptType,
      content: '我需要了解关于[主题]的信息，特别是[具体方面]。你能提供相关的解释和例子吗？',
      description: '用户问题的通用模板，可以根据需要填充具体主题',
      tags: ['问题', '模板', '用户'],
      createdAt: '2023-10-04',
      updatedAt: '2023-10-04'
    },
    {
      id: '5',
      name: '幽默回答模式',
      type: 'assistant' as PromptType,
      content: '当然，我很乐意帮助你！让我用一点幽默感来解释这个问题...[内容]希望这个解释既有用又让你开心！',
      description: '带有幽默风格的助手回答模板',
      tags: ['幽默', '风格', '助手'],
      createdAt: '2023-10-05',
      updatedAt: '2023-10-05'
    }
  ];
};

// 获取提示词列表 - 使用Mock数据
const fetchPromptList = () => {
  loading.value = true;
  
  // 模拟API请求延迟
  setTimeout(() => {
    promptList.value = generateMockPromptList();
    loading.value = false;
  }, 300);
};

// 显示创建提示词对话框
const showCreateModal = () => {
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 编辑提示词
const editPrompt = (prompt: PromptItem) => {
  isEdit.value = true;
  currentPrompt.value = prompt;
  
  // 填充表单数据
  formState.name = prompt.name;
  formState.type = prompt.type;
  formState.content = prompt.content;
  formState.description = prompt.description || '';
  formState.tags = prompt.tags || [];
  
  modalVisible.value = true;
};

// 删除提示词
const deletePrompt = (id: string) => {
  // 模拟删除操作
  promptList.value = promptList.value.filter(item => item.id !== id);
  message.success('删除成功');
};

// 处理模态框确认
const handleModalOk = () => {
  formRef.value.validate().then(() => {
    if (isEdit.value && currentPrompt.value) {
      // 编辑模式
      const index = promptList.value.findIndex(item => item.id === currentPrompt.value?.id);
      if (index !== -1) {
        promptList.value[index] = {
          ...currentPrompt.value,
          name: formState.name,
          type: formState.type,
          content: formState.content,
          description: formState.description,
          tags: formState.tags,
          updatedAt: new Date().toISOString().split('T')[0]
        };
        message.success('更新提示词成功');
      }
    } else {
      // 创建模式
      promptList.value.unshift({
        id: Math.random().toString(36).substring(2, 11),
        name: formState.name,
        type: formState.type,
        content: formState.content,
        description: formState.description,
        tags: formState.tags,
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0]
      });
      message.success('创建提示词成功');
    }
    
    modalVisible.value = false;
  }).catch((error: any) => {
    console.log('表单验证失败', error);
  });
};

// 取消模态框
const handleModalCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  currentPrompt.value = null;
  formState.name = '';
  formState.type = 'system' as 'system' | 'user' | 'assistant';
  formState.content = '';
  formState.description = '';
  formState.tags = [];
};

onMounted(() => {
  fetchPromptList();
});
</script>

<style scoped>
.prompt-manage-container {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.prompt-list {
  margin-top: 16px;
}

.delete-link {
  color: #ff4d4f;
}
</style> 